﻿const mongoose = require('mongoose');

mongoose.connect('mongodb+srv://haochen214_db_user:h@castle0.2ho5jpg.mongodb.net/?retryWrites=true&w=majority&appName=Castle0')
    .then(() =>
       console.log('Connected to MongoDB...')
    )
    .catch(err => console.log('Could not connect to MongoDB...',err));


const courseSchema = new mongoose.Schema({
   name: {
       type:String,
       required:true,
       minLength:5,
       maxLength:255
   },
   author:String,
   tags:{
       type:Array,
        validate:function(v){
            return v.length > 0;
        },
       message:'A course should have at least one tag'
    },
   date:{ type:Date,default:Date.now },
   isPublished:Boolean
});

const Course = mongoose.model('Course',courseSchema);

async function createCourse(){
    const course = new Course({
        name:'Node.js Course',
        author:'Mosh',
        tags:['node','backend'],
        isPublished:true,
        price:{
            type:Number,
            required:function (){
                return this.isPublished;
            }
        }
    });
    try {

        const result = await course.save();
        console.log(result);
    }catch(ex){
        console.log(ex.message);
    }

}

async function getCourses(){
    // eq-equal
    // ne-not equal
    // gt-greater than
    // gte-greater than or equal to
    // lt-less than
    // lte-less than or equal to
    // in
    // nin-not in
    const courses = await Course
        .find({
        price:{ $gte:10,$lte:20}
    }).limit(10).sort({name:1}).select({name:1,tags:1});
    console.log(courses);
}

getCourses();




